<script lang="ts" setup>
import { isApp, isAppAndroid, isAppHarmony, isAppIOS, isAppPlus, isH5, isMpWeixin, isWeb } from '@uni-helper/uni-env'
import { nextTick, onMounted, ref } from 'vue'
import { getRect, isArray } from 'wot-design-uni/components/common/util'
import { useThemeStore } from '@/store'

import { appConfig } from './appConfig.ts' // 导入我们刚刚创建的配置文件

defineOptions({
  name: 'Home',
})

console.log({ isApp, isAppAndroid, isAppHarmony, isAppIOS, isAppPlus, isH5, isMpWeixin, isWeb })

definePage({
  // 使用 type: "home" 属性设置首页，其他页面不需要设置，默认为page
  type: 'home',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    // navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
})
const themeStore = useThemeStore()

const active = ref<number>(1)
const scrollTop = ref<number>(0)
const itemScrollTop = ref<number[]>([])
// 生成独立的子项数据，避免引用共享
const subCategories = Array.from({ length: 24 }, (_, i) => ({
  title: `标题${i + 1}`,
  label: `这是第${i + 1}个描述信息`,
  id: `sub-${i}`, // 增加唯一ID，避免循环key用索引（索引不稳定）
}))
const categories = ref([
  {
    label: '湘味特色', // 突出湘菜核心，吸引目标客群
    title: '湘味特色',
    icon: 'hotjar', // 用“辣椒/热辣”图标，贴合湘菜“辣”的属性
    items: subCategories, // 放剁椒鱼头、小炒黄牛肉、湘西腊肉等招牌湘菜
  },
  {
    label: '圆圆爱吃的小炒', // 核心热菜类，顾客优先看
    title: '圆圆爱吃的小炒',
    icon: 'fire', // 用“火焰”图标，直观体现“炒制”属性（替代原 qrcode）
    items: subCategories,
  },
  {
    label: '田园时蔬', // 素菜类，搭配小炒解腻
    title: '田园时蔬',
    icon: 'leaf', // 用“叶子”图标，贴合“蔬菜”属性（替代原 thumb-up）
    items: subCategories.slice(0, 18),
  },
  {
    label: '养胃暖汤', // 修正“暖烫”为“暖汤”，更符合餐饮用语
    title: '养胃暖汤',
    icon: 'droplet', // 用“水滴/汤水”图标，直观体现“汤品”（替代原 ie）
    items: subCategories.slice(0, 21),
  },
  {
    label: '馋嘴小食', // 小吃类，适合加餐/凑单
    title: '馋嘴小食',
    icon: 'snack', // 用“零食”图标，贴合“小食”属性（替代原 ie）
    items: subCategories.slice(0, 21),
  },
  {
    label: '米饭主食', // 刚需主食，搭配菜品
    title: '米饭主食',
    icon: 'fork-spoon', // 用“餐具”图标，比 github-filled 更贴合“主食”场景
    items: subCategories,
  },
  {
    label: '酒水饮料', // 饮品类，解辣/解渴（尤其适配湘菜等重口品类）
    title: '酒水饮料',
    icon: 'glass', // 用“杯子”图标，直观体现“饮品”（替代原 chrome）
    items: subCategories.slice(0, 18),
  },
])

const greetingText = ref('')
const weatherTip = ref('')
const appName = ref('')
const description = ref('')
const dailyDish = ref('')
const dailyReason = ref('')

// 模拟获取天气（实际项目中可以调用天气API）
function getWeather(): string {
  const weathers = ['sunny', 'rainy', 'cloudy', 'snowy']
  return weathers[Math.floor(Math.random() * weathers.length)] as keyof typeof appConfig.weatherTips
}

// 根据时间获取问候语
function getGreetingByTime(): string {
  const hour = new Date().getHours()
  if (hour < 6)
    return appConfig.greetings.night
  if (hour < 12)
    return appConfig.greetings.morning
  if (hour < 18)
    return appConfig.greetings.noon
  return appConfig.greetings.evening
}

onMounted(async () => {
  // 设置动态文案
  appName.value = appConfig.appName
  description.value = appConfig.description
  greetingText.value = getGreetingByTime()

  const weather = getWeather()
  weatherTip.value = appConfig.weatherTips[weather]

  // --- 修改这部分 ---
  // 获取今日推荐并赋值
  const todaysRecommendation = getDailyRecommendation()
  dailyDish.value = todaysRecommendation.dish
  dailyReason.value = todaysRecommendation.reason
  try {
    console.log('1. onMounted 开始执行...')

    // 等待 Vue 完成 DOM 更新（关键步骤！）
    await nextTick()
    console.log('2. nextTick 完成，DOM 已更新，可以安全地获取元素了。')

    // 获取所有 .category 元素的位置信息
    const rects = await getRect('.category', true)
    console.log('3. getRect 执行完毕，返回结果:', rects)

    // 进行严格的类型和长度判断，确保代码健壮性
    if (isArray(rects) && rects.length > 0) {
      itemScrollTop.value = rects.map(item => item.top || 0)
      console.log('4. itemScrollTop 设置成功:', itemScrollTop.value)

      // 确保 active 的值在有效范围内
      const targetIndex = active.value < rects.length ? active.value : 0
      scrollTop.value = rects[targetIndex].top || 0
      console.log(`5. scrollTop 设置为: ${scrollTop.value}`)
    }
    else {
      // 如果没找到元素，给出明确的警告
      console.warn('警告：未能获取到 .category 元素的位置信息，请检查模板中的 class 或数据是否正确。')
    }
  }
  catch (error) {
    // 如果任何一步出错，这里会捕获到真正的错误
    console.error('!!! onMounted 内部发生了致命错误:', error)
  }
})
function getDailyRecommendation() {
  const recommendations = appConfig.dailyRecommendations
  const now = new Date()
  const start = new Date(now.getFullYear(), 0, 0)
  const diff = (now as any) - (start as any)
  const oneDay = 1000 * 60 * 60 * 24
  const dayOfYear = Math.floor(diff / oneDay)
  // 每天都会从新的湘菜数组中选择一个
  const todaysRecommendation = recommendations[dayOfYear % recommendations.length]
  return todaysRecommendation
}
function handleChange({ value }) {
  active.value = value
  scrollTop.value = itemScrollTop.value[value]
}
function onScroll(e) {
  const { scrollTop } = e.detail
  const threshold = 50 // 下一个标题与顶部的距离
  if (scrollTop < threshold) {
    active.value = 0
    return
  }
  const index = itemScrollTop.value.findIndex(top => top > scrollTop && top - scrollTop <= threshold)
  if (index > -1) {
    active.value = index
  }
}
</script>

<template>
  <!-- --- 新增的动态文案展示区域 --- -->
  <view class="header-banner">
    <view class="greeting">
      <text class="greeting-text">{{ greetingText }}</text>
      <text v-if="weatherTip" class="weather-tip">💬 {{ weatherTip }}</text>
    </view>
    <view class="app-info">
      <text class="app-name">{{ appName }}</text>
      <text class="app-description">{{ description }}</text>
    </view>

    <!-- 今日推荐卡片 -->
    <wd-card class="daily-recommendation" :border="false">
      <template #header>
        <view class="recommendation-header">
          <wd-icon name="heart" color="#ff4d6d" size="18" />
          <text class="recommendation-title">今日份宠爱</text>
        </view>
      </template>
      <view class="recommendation-content">
        <text class="dish-name">🍲 {{ dailyDish }}</text>
        <text class="dish-reason">💌 {{ dailyReason }}</text>
      </view>
    </wd-card>
  </view>
  <!-- --- 动态文案展示区域结束 --- -->
  <view class="wraper">
    <wd-sidebar v-model="active" @change="handleChange">
      <wd-sidebar-item v-for="(item, index) in categories" :key="index" :value="index" :label="item.label" :icon="item.icon" />
    </wd-sidebar>
    <scroll-view class="content" scroll-y scroll-with-animation :scroll-top="scrollTop" :throttle="true" :throttle-time="100" @scroll="onScroll">
      <view v-for="(item, index) in categories" :key="index" class="category">
        <wd-cell-group :title="item.title" border>
          <wd-cell v-for="(cell, index) in item.items" :key="index" :title="cell.title" :label="cell.label">
            <wd-icon name="github-filled" size="24px" />
          </wd-cell>
        </wd-cell-group>
      </view>
    </scroll-view>
  </view>
</template>

<style scoped lang="scss">
.wraper {
  display: flex;
  height: calc(100vh - var(--window-top));
  height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom));
  height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));
}
.content {
  flex: 1;
  background: #fff;
}

/* --- 新增的样式 --- */
.header-banner {
  padding: 24rpx;
  background: linear-gradient(135deg, #fff0f3 0%, #ffe6ec 100%);
  border-radius: 16rpx;
  margin: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(255, 100, 130, 0.1);
}
.greeting {
  margin-bottom: 16rpx;
  .greeting-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #d6336c;
  }
  .weather-tip {
    font-size: 24rpx;
    color: #e74c3c;
    margin-left: 16rpx;
  }
}
.app-info {
  margin-bottom: 24rpx;
  .app-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #d6336c;
    display: block;
  }
  .app-description {
    font-size: 28rpx;
    color: #e74c3c;
    opacity: 0.8;
  }
}
.daily-recommendation {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12rpx;
  .recommendation-header {
    display: flex;
    align-items: center;
    .recommendation-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #d6336c;
      margin-left: 8rpx;
    }
  }
  .recommendation-content {
    padding: 16rpx 0 8rpx 0;
    .dish-name {
      font-size: 30rpx;
      font-weight: bold;
      color: #c0392b;
      display: block;
      margin-bottom: 8rpx;
    }
    .dish-reason {
      font-size: 24rpx;
      color: #7f8c8d;
      line-height: 1.5;
    }
  }
}
/* --- 新增样式结束 --- */

::v-deep(.wd-sidebar-item-active) {
  // ::v-deep 穿透 scoped 修改子组件样式
  color: #165dff; // 自定义激活态文字颜色
  .wd-sidebar-item-icon {
    color: #165dff; // 自定义激活态图标颜色
  }
}
</style>
